package com.project.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.project.bean.UserBean;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.time.LocalDate;

//标识该类为应用控制器类
@Controller
@RequestMapping("user")
public class TestController {

    //标识该方法的请求URL路径
    @RequestMapping("test")
    public String  test(){
        System.out.println("访问test");

        //重定向到指定页面
        return "redirect:/html/index.html";
    }

    @RequestMapping("/add")
    public String  add(UserBean user,String name,
                       @RequestParam("money") int m) throws Exception {
        System.out.println(user+"    "+name+"   "+m);
        return "redirect:/html/index.html";
    }

    @RequestMapping("/speak")
    public void speak(HttpServletRequest request,HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().print("hello，迟到四人组");
    }

    @RequestMapping("/testUrl/{aaa}")
    public void testUrl(@PathVariable("aaa") int id){
        System.out.println("id="+id);
    }

    @RequestMapping("/cut")
    public void cut(
            @RequestParam(value = "pg",defaultValue = "1") int pageNO){
        System.out.println("pageNO="+pageNO);
    }

    @RequestMapping("/getObj")
    public void getObj(HttpServletResponse response) throws Exception{
        response.setContentType("text/html;charset=utf-8");
        UserBean user = new UserBean(1,"张三 ","111",3000, LocalDate.parse("1998-03-02"));
        ObjectMapper om = new ObjectMapper();
        om.registerModule(new JavaTimeModule());
        String str = om.writeValueAsString(user);
        response.getWriter().print(str);
        OutputStream out  = response.getOutputStream();
    }

    @RequestMapping("/getUser")
    @ResponseBody
    public String getUser() throws Exception{
        UserBean user = new UserBean(1,"张三 ","111",3000, LocalDate.parse("1998-03-02"));
        return "ok";
    }
}
